package com.cetc.oauth2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.sql.ResultSet;
import java.sql.SQLException;

public class JwtService implements UserDetailsService {

    private final String FIND_USER_BY_USERNAME="select id,user_name,password,display_name from login_user where user_name=?";

    private final String JWT_TOKEN_INSERT="insert into jwt_token(jwt_token,login_user,create_time,lose_time) values(?,?,?,?)";

    private final String JWT_TOKEN_DELETE="delete from jwt_token where login_user=?";

    @Autowired
    private JdbcTemplate jdbcTemplate;



    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserDetails userDetails=jdbcTemplate.queryForObject(FIND_USER_BY_USERNAME, new Object[]{s}, new RowMapper<UserDetails>() {
            @Override
            public UserDetails mapRow(ResultSet rs, int i) throws SQLException {
                UserDetails userDetails=User.withUsername(rs.getString("user_name"))
                        .accountLocked(false).accountExpired(false).password(rs.getString("password"))
                        .roles("USER").build();
                return userDetails;
            }
        });

        return userDetails;
    }

    /**
     * 根据登录名删除token
     * @param userName
     */
    public void deleteUserLoginInfo(String userName){
        jdbcTemplate.update(JWT_TOKEN_DELETE,userName);
    }

}
